import { Injectable, Injector } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { catchError, Observable, throwError } from 'rxjs';
import { CoreService } from 'src/core/service/core.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { Router } from '@angular/router';
import { CmdSignModel } from 'src/core/module/CmdSignModel';
import { SessionCmdCode } from 'src/module/module-home/core';
import { environment } from '../environments/environment';

@Injectable()
export class HttpService {

  baseUrl = environment.host;
  protected http: HttpClient;
	private coreService: CoreService;
  
  constructor(
    protected injector: Injector,
    protected message: NzMessageService,
    private router: Router
    ) {
    this.http = injector.get(HttpClient);
		this.coreService = injector.get(CoreService);
   }

  public exe(cmdSign: CmdSignModel):Promise<any> {
		let headers = new HttpHeaders({ 'Content-Type': 'application/json' });

    let jwt = this.coreService.getToken();
		if (jwt) {
      cmdSign.token = jwt;
		}else{
      if(cmdSign.cmdCode !== SessionCmdCode.SOP_MEMBER_POST){
        this.message.error("会话过期");
        this.router.navigateByUrl('/login');
        return new Promise((resovle)=>{});
      }
    }
    let that = this;
    cmdSign.source = JSON.stringify(cmdSign.source);
    cmdSign.scope = "sop";
    let promise = new Promise((resovle) => {
      that.http.post(this.baseUrl+"/sop/api", cmdSign, { headers: headers }).pipe(
        catchError(this.handleError)
      ).subscribe((res:any) => {
        if(res.respCode === 410){
          this.coreService.clearToken();
          this.message.error("会话过期!");
          this.router.navigateByUrl('/login');
        }else if(res.respCode !== 200){
          this.message.error(res.msg);
          new Error("系统错误!");
        }else{
          res.source = JSON.parse(res.source);
          resovle(res);
        }
      });
    })
    return promise;
	}

  public exeSync(cmdSign: CmdSignModel):Observable<any> {
		let headers = new HttpHeaders({ 'Content-Type': 'application/json' });

		let userModel = this.coreService.getUserModel();
    let jwt = sessionStorage.getItem("ADMIN_JWT_NAME");
		if (jwt) {
      headers = headers.set('ADMIN_JWT_NAME', jwt);
		}else{
      // if(url.indexOf("session") === -1 && url.indexOf("register") === -1){
      //   this.message.error("会话过期");
      //   this.router.navigateByUrl("/login");
      // }
    }
    cmdSign.source = JSON.stringify(cmdSign.source);
    return this.http.post("http://127.0.0.1:8888/admin/api", cmdSign, { headers: headers }).pipe(catchError(this.handleError));;
	}

  private handleError(error: Response | any) {
		// In a real world app, we might use a remote logging infrastructure
		let errMsg: string;
    console.log(error)
		if (error instanceof Response) {
			const body: any = error.json() || '';
			const err = body.error || JSON.stringify(body);
			errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
		} else {
			errMsg = error.message ? error.message : error.toString();
		}
		console.error(error);
		return throwError(errMsg);
	}
}
